package sasp_messages;



import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author j
 */

public class SASP_RSACipher {

	private PrivateKey privKey;
        private PublicKey pubKey;
        private Cipher rsaCipher;

        public PublicKey getPubKey()    {
                return pubKey;
        }

        /*
         * encrypt wraps up an AES SecretKey to pass to another user using their public RSA key (this.pubKey)
         */
        public byte[] encrypt(SecretKey _sessionKey, PublicKey _pubKey) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException	{
                rsaCipher.init(Cipher.ENCRYPT_MODE, _pubKey);
                byte[] encodedKey = rsaCipher.doFinal(_sessionKey.getEncoded());
                return encodedKey;
        }

        /*
         * decrypt unwraps an AES SecretKey with the user's private RSA key (this.privKey)
         */
	public SecretKey decrypt(byte[] _encodedKey) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeySpecException	{
		rsaCipher.init(Cipher.DECRYPT_MODE, privKey);
		byte[] _decodedKey = rsaCipher.doFinal(_encodedKey);
                SecretKeySpec _keySpec = new SecretKeySpec(_decodedKey, "AES");
                SecretKeyFactory factory = SecretKeyFactory.getInstance("AES");
                return factory.generateSecret(_keySpec);
	}

        /*
         * loadMyKey takes in the filename and path of the RSA pair the user wishes to load
         */
        public void loadMyKey(String fileName, String path) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, ClassNotFoundException   {
            SASP_RSA rsaFile = new SASP_RSA();
            rsaFile.setPath(path);
            pubKey = rsaFile.loadPub(fileName);
            privKey = rsaFile.loadPriv(fileName);
        }

        /*
         * generateKey() only called when needing new RSA keypairs
         */
        public void generateKey(String fileName, String _filePath) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException   {
            SASP_RSA rsaFile = new SASP_RSA();
            rsaFile.setPath(_filePath);
            rsaFile.makeRSA();
            rsaFile.saveRSA(fileName);
        }

	public SASP_RSACipher() throws NoSuchAlgorithmException, NoSuchPaddingException	{
                rsaCipher = Cipher.getInstance("RSA");
	}



}
